import { _decorator, Animation, Collider2D, Component, Contact2DType, Director, director, input, Input, Node, RigidBody2D, tween, v2, v3 } from 'cc';
import { AudioConfig, GGType, RigidGroup } from './config/game-param';
import { EventManager } from './manager/event';
import { AudioMgr } from './AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('Bird')
export class Bird extends Component {
    @property(Node) bird: Node

    private _ctrl: boolean = false
    private speed: number = 0
    private animFly: Animation
    private rigidBody: RigidBody2D

    onLoad() {
        this.animFly = this.bird.getComponent(Animation)

        this.rigidBody = this.bird.getComponent(RigidBody2D)
        this.rigidBody.enabled = false

        input.on(Input.EventType.TOUCH_START, this.onTapJump, this)
    }

    start() {
        const collider = this.bird.getComponent(Collider2D)
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this)
        }
    }

    update(dt: number) {
        if (!this._ctrl) return
        if (this.bird.angle > -80) this.bird.angle -= 0.5
    }

    startGame() {
        this.bird.setRotation(0, 0, 0, 1)
        this._ctrl = true
        this.animFly.play('bird-fly')
        this.rigidBody.enabled = true
    }

    stopGame() {
        this._ctrl = false
        this.animFly.stop()
        this.rigidBody.enabled = false
    }

    resetPosition() {
        // 这里设置angle没更新，估计这个angle不是立即执行的，换成setRotation
        this.bird.setRotation(0, 0, 0, 1)
        tween(this.bird).to(0.5, { position: v3(0, 0, 0) }).start()
    }

    onTapJump() {
        if (this._ctrl === false) return
        
        // 施加升力
        const lift = v2(0, 15)
        this.rigidBody.linearVelocity  = lift
        this.bird.angle = 20

        AudioMgr.inst.playOneShot(AudioConfig.SWOOSH)
    }

    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D) {
        let colliderType: GGType = null
        switch (otherCollider.group) {

            case RigidGroup.BIRD:
                // TODO
                break

            case RigidGroup.PIPE:
                colliderType = GGType.CollisionPipe
                break

            case RigidGroup.GROUND:
                colliderType = GGType.FailGround
                break
        
            default:
                break
        }

        if(colliderType !== null) {
            director.once(Director.EVENT_AFTER_PHYSICS, () => {
                EventManager.emit('on-collider', colliderType)
            }, this)
        }
    }

    onDestroy() {
        input.off(Input.EventType.TOUCH_START, this.onTapJump, this)

        const collider = this.bird.getComponent(Collider2D)
        if (collider) {
            collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this)
        }
    }
 }


